package com.easychat.mychat.chatservice.service.impl;

import com.easychat.mychat.chatservice.entity.po.ChatMessage;
import com.easychat.mychat.chatservice.entity.po.ChatSession;
import com.easychat.mychat.chatservice.entity.po.ChatSessionUser;
import com.easychat.mychat.chatservice.entity.po.GroupInfo;
import com.easychat.mychat.chatservice.entity.query.ChatMessageQuery;
import com.easychat.mychat.chatservice.entity.query.ChatSessionQuery;
import com.easychat.mychat.chatservice.entity.query.ChatSessionUserQuery;
import com.easychat.mychat.chatservice.entity.query.GroupInfoQuery;
import com.easychat.mychat.chatservice.mapper.ChatMessageMapper;
import com.easychat.mychat.chatservice.mapper.ChatSessionMapper;
import com.easychat.mychat.chatservice.mapper.ChatSessionUserMapper;
import com.easychat.mychat.chatservice.mapper.GroupInfoMapper;

import com.easychat.mychat.chatservice.service.ChatSessionUserService;
import com.easychat.mychat.chatservice.service.GroupInfoService;
import com.easychat.mychat.common.Redis.RedisComponent;
import com.easychat.mychat.common.entity.config.AppConfig;
import com.easychat.mychat.common.entity.constants.Constants;
import com.easychat.mychat.common.entity.dto.MessageSendDto;
import com.easychat.mychat.common.entity.dto.SysSettingDto;
import com.easychat.mychat.common.entity.dto.TokenUserInfoDto;
import com.easychat.mychat.common.entity.enums.*;
import com.easychat.mychat.common.entity.po.UserContact;
import com.easychat.mychat.common.entity.po.UserInfo;
import com.easychat.mychat.common.entity.query.SimplePage;
import com.easychat.mychat.common.entity.query.UserContactQuery;
import com.easychat.mychat.common.entity.query.UserInfoQuery;
import com.easychat.mychat.common.entity.vo.PaginationResultVO;
import com.easychat.mychat.common.exception.BusinessException;
import com.easychat.mychat.common.utils.CopyTools;
import com.easychat.mychat.common.utils.StringTools;
import com.easychat.mychat.common.webSocket.ChannelContextUtils;
import com.easychat.mychat.common.webSocket.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 业务接口实现
 */
@Service("groupInfoService")
public class GroupInfoServiceImpl implements GroupInfoService {

    private static final Logger logger = LoggerFactory.getLogger(GroupInfoServiceImpl.class);

    @Resource
    private AppConfig appConfig;

    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;

    @Resource
    private RedisComponent redisComponet;

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private UserContactService userContactService;

    @Resource
    @Lazy
    private GroupInfoService groupInfoService;

    @Resource
    private ChatSessionUserMapper<ChatSessionUser, ChatSessionUserQuery> chatSessionUserMapper;
    @Resource
    private ChatSessionMapper<ChatSession, ChatSessionQuery> chatSessionMapper;
    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;

    @Resource
    private MessageHandler messageHandler;

    @Resource
    private ChannelContextUtils channelContextUtils;
    @Resource
    private ChatSessionUserService chatSessionUserService;
    /**
     * 根据条件查询列表
     */
    @Override
    public List<GroupInfo> findListByParam(GroupInfoQuery param) {
        return this.groupInfoMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(GroupInfoQuery param) {
        return this.groupInfoMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<GroupInfo> findListByPage(GroupInfoQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<GroupInfo> list = this.findListByParam(param);
        PaginationResultVO<GroupInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(GroupInfo bean) {
        return this.groupInfoMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<GroupInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.groupInfoMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<GroupInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.groupInfoMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(GroupInfo bean, GroupInfoQuery param) {
        StringTools.checkParam(param);
        return this.groupInfoMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(GroupInfoQuery param) {
        StringTools.checkParam(param);
        return this.groupInfoMapper.deleteByParam(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGroup(TokenUserInfoDto tokenUserInfo, String groupId, String groupName, String groupNotice, Integer joinType, MultipartFile avatarCover, MultipartFile avatarFile) {
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGroupName(groupName);
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setStatus(GroupStatusEnum.NORMAL.getStatus());
        groupInfo.setJoinType(joinType);
        Date curDate = new Date();
        //修改群信息
        if (groupId != null){
            GroupInfo dbGroupInfo = groupInfoMapper.selectByGroupId(groupId);
            if (!dbGroupInfo.getGroupOwnerId().equals(tokenUserInfo.getUserId())){
                throw new BusinessException(ResponseCodeEnum.CODE_600);
            }
            groupInfoMapper.updateByGroupId(groupInfo,groupId);

            String contactNameUpdate = null;
            if (dbGroupInfo.getGroupName().equals(groupName)){
                return;
            }
            contactNameUpdate = groupName;
            chatSessionUserService.updateRedundanceInfo(contactNameUpdate,groupId);

        }
        //新增群聊
        else {
            GroupInfoQuery query = new GroupInfoQuery();
            SysSettingDto sysSettingDto = redisComponet.getSysSetting();

            query.setGroupOwnerId(tokenUserInfo.getUserId());
            query.setStatus(GroupStatusEnum.NORMAL.getStatus());
            Integer i = groupInfoMapper.selectCount(query);
            //判断创建群数是否满
            if (i >= sysSettingDto.getMaxGroupCount()){
                throw new BusinessException("最多支持创建"+ sysSettingDto.getMaxGroupCount() + "个群聊");
            }

            //添加群信息
            groupId = StringTools.getGroupId();
            GroupInfo info = groupInfoMapper.selectByGroupId(groupId);
            if (info != null) {
                throw new BusinessException(ResponseCodeEnum.CODE_600);
            }
            groupInfo.setGroupId(groupId);

            groupInfo.setGroupOwnerId(tokenUserInfo.getUserId());
            groupInfo.setCreateTime(curDate);
            groupInfoMapper.insert(groupInfo);

            //将群组添加至群里
            UserContact userContact = new UserContact();
            userContact.setStatus(UserContactStatusEnum.FRIEND.getStatus());
            userContact.setContactType(UserContactTypeEnum.GROUP.getType());
            userContact.setUserId(tokenUserInfo.getUserId());
            userContact.setCreateTime(curDate);
            userContact.setContactId(groupId);
            userContact.setLastUpdateTime(curDate);
            userContactMapper.insert(userContact);

            String sessionId = StringTools.getChatSessionId4Group(groupId);
            ChatSession groupSession = new ChatSession();
            groupSession.setSessionId(sessionId);
            groupSession.setLastMessage(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            groupSession.setLastReceiveTime(curDate.getTime());
            chatSessionMapper.insertOrUpdate(groupSession);

            //群主与群关联
            ChatSessionUser chatSessionUser = new ChatSessionUser();
            chatSessionUser.setSessionId(sessionId);
            chatSessionUser.setUserId(tokenUserInfo.getUserId());
            chatSessionUser.setContactId(groupId);
            chatSessionUser.setContactName(groupName);
            chatSessionUserMapper.insertOrUpdate(chatSessionUser);

            //创建消息
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum.GROUP_CREATE.getType());
            chatMessage.setMessageContent(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            chatMessage.setSendTime(curDate.getTime());
            chatMessage.setContactId(groupId);
            chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
            chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());

            chatMessageMapper.insert(chatMessage);

            redisComponet.addUserContact(tokenUserInfo.getUserId(),groupId);
            channelContextUtils.addUser2Group(tokenUserInfo.getUserId(),groupId);

            //发送ws消息
            chatSessionUser.setLastMessage(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            chatSessionUser.setLastReceiveTime(curDate.getTime());
            chatSessionUser.setMemberCount(1);

            MessageSendDto messageSendDto = CopyTools.copy(chatMessage,MessageSendDto.class);
            messageSendDto.setExtendData(chatSessionUser);
            messageSendDto.setLastMessage(MessageTypeEnum.GROUP_CREATE.getInitMessage());
            messageHandler.sendMessage(messageSendDto);
        }
        if (null == avatarFile){
            return;
        }

        String path = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
        File targetFile  = new File(path);
        if (!targetFile.exists()){
            targetFile.mkdirs();
        }

        String filePath = targetFile.getPath() + "/" + groupId;
        try {
            avatarFile.transferTo(new File(filePath + Constants.IMAGE_SUFFIX));
            avatarCover.transferTo(new File(filePath + Constants.COVER_IMAGE_SUFFIX));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<GroupInfo> loadMyGroup(TokenUserInfoDto tokenUserInfo) {
        GroupInfoQuery query = new GroupInfoQuery();
        query.setGroupOwnerId(tokenUserInfo.getUserId());
        query.setOrderBy("create_time desc");
        query.setStatus(GroupStatusEnum.NORMAL.getStatus());
        List<GroupInfo> groupInfos = groupInfoMapper.selectList(query);
        return groupInfos;
    }

    @Override
    public GroupInfo getGroupInfo(TokenUserInfoDto tokenUserInfo, String groupId) {
        String userId = tokenUserInfo.getUserId();
        UserContact userContact = userContactMapper.selectByUserIdAndContactId(userId, groupId);
        if (userContact == null || !userContact.getStatus().equals(UserContactStatusEnum.FRIEND.getStatus())){
            throw new BusinessException("你不在群聊或者群聊已解散");
        }
        GroupInfo groupInfo = groupInfoMapper.selectByGroupId(groupId);
        if (groupInfo == null || !groupInfo.getStatus().equals(GroupStatusEnum.NORMAL.getStatus())){
            throw new BusinessException("群聊不存在或已解散");
        }

        //查询人数
        UserContactQuery query = new UserContactQuery();
        query.setContactId(groupId);
        query.setStatus(UserContactStatusEnum.FRIEND.getStatus());

        Integer i = userContactMapper.selectCount(query);
        groupInfo.setMemberCount(i);
        return groupInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void leaveGroup(TokenUserInfoDto tokenUserInfo, String groupId) {
        GroupInfo groupInfo = groupInfoMapper.selectByGroupId(groupId);
        if (groupInfo == null || groupInfo.getStatus().equals(GroupStatusEnum.DISSOLUTION.getStatus())){
            throw new BusinessException("群聊已解散或不存在");
        }
        UserContact userContact = userContactMapper.selectByUserIdAndContactId(tokenUserInfo.getUserId(), groupId);
        if (userContact == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (userContact.getStatus().equals(UserContactStatusEnum.DEL_BE.getStatus())){
            throw new BusinessException("您已被移除群聊");
        }
        userContact.setStatus(UserContactStatusEnum.DEL.getStatus());
        userContact.setLastUpdateTime(new Date());
        Integer i = userContactMapper.insertOrUpdate(userContact);
        if (i != 1){
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dissolutionGroup(String groupOwnerId, String groupId) {
        GroupInfo groupInfo = groupInfoMapper.selectByGroupId(groupId);
        //删除群组
        GroupInfo updateInfo = new GroupInfo();
        updateInfo.setStatus(GroupStatusEnum.DISSOLUTION.getStatus());
        groupInfoMapper.updateByGroupId(updateInfo,groupId);
//        groupInfoMapper.deleteByGroupId(groupId)
        //改联系人
        UserContactQuery query = new UserContactQuery();
        query.setContactId(groupId);
        query.setContactType(UserContactTypeEnum.GROUP.getType());

        UserContact userContact = new UserContact();
        userContact.setStatus(UserContactStatusEnum.DEL.getStatus());

        List<UserContact> userContactList = userContactMapper.selectList(query);
        userContactMapper.updateByParam(userContact,query);

        //移除缓存
        for (UserContact contact : userContactList) {
            redisComponet.removeUserContact(contact.getUserId(), groupId);
        }

        ChatSessionUserQuery chatSessionUserQuery = new ChatSessionUserQuery();
        chatSessionUserQuery.setContactId(groupId);
        chatSessionUserQuery.setUserId(groupOwnerId);
        ChatSessionUser chatsession = chatSessionUserMapper.selectByUserIdAndContactId(groupOwnerId, groupId);
        String sessionId = chatsession.getSessionId();

        ChatSession chatSession = new ChatSession();
        chatSession.setSessionId(sessionId);
        chatSession.setLastMessage(MessageTypeEnum.DISSOLUTION_GROUP.getInitMessage());
        chatsession.setLastReceiveTime(System.currentTimeMillis());
        chatSessionMapper.updateBySessionId(chatSession,sessionId);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        chatMessage.setSessionId(sessionId);
        chatMessage.setMessageType(MessageTypeEnum.DISSOLUTION_GROUP.getType());
        chatMessage.setMessageContent(MessageTypeEnum.DISSOLUTION_GROUP.getInitMessage());
        chatMessage.setSendTime(System.currentTimeMillis());
        chatMessage.setContactId(groupId);
        chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());

        chatMessageMapper.insert(chatMessage);

        MessageSendDto messageSendDto = CopyTools.copy(chatMessage, MessageSendDto.class);
        messageSendDto.setLastMessage(MessageTypeEnum.DISSOLUTION_GROUP.getInitMessage());

        messageHandler.sendMessage(messageSendDto);
    }

    @Override
    public GroupInfo getGroupInfoByGroupId(String groupId) {
        GroupInfo groupInfo = groupInfoMapper.selectByGroupId(groupId);
        return groupInfo;
    }

    @Override
    public void addOrRemoveGroupUser(String userId, String groupId, String selectContacts, Integer opType) {
        if (selectContacts == null || selectContacts.isEmpty()){
            throw new BusinessException("请添加联系人");
        }
        //查询群组
        GroupInfo groupInfo = groupInfoMapper.selectByGroupId(groupId);
        if (groupInfo == null){
            throw new BusinessException("群聊不存在");
        }
        if (!userId.equals(groupInfo.getGroupOwnerId())){
            throw new BusinessException("没有权限进行操作");
        }
        String[] split = selectContacts.split(",");
        Date curDate = new Date();
        List<UserContact> userContactList = new ArrayList<>();
        for (String s : split) {
            UserContact userContact = new UserContact();
            userContact.setContactId(groupId);
            userContact.setUserId(s);
            userContact.setLastUpdateTime(curDate);
            userContact.setCreateTime(curDate);
            userContact.setContactType(UserContactTypeEnum.GROUP.getType());
            userContact.setStatus(UserContactStatusEnum.FRIEND.getStatus());
            userContactList.add(userContact);
        }
        //移除
        if (opType.equals(Constants.ZERO)){
            userContactMapper.insertOrUpdateBatch(userContactList);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
            MessageSendDto messageSendDto = new MessageSendDto();

        }
    }
}